package com.contest.listener;

import com.contest.quartz.QuartzManager;
import com.contest.quartz.data.ScheduleJob;
import com.contest.quartz.task.TaskCheckGameNumbers;
import com.contest.quartz.task.TaskTest;
import com.contest.service.GameNumbersRuleService;
import com.contest.util.SpringContextHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.XmlWebApplicationContext;

@Component
public class SimpleApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    Logger logger = LoggerFactory.getLogger(SimpleApplicationListener.class);
    private volatile static boolean flag = true;

    @Autowired
    GameNumbersRuleService gameNumbersRuleService;

    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        Object obj = contextRefreshedEvent.getSource();
        if(obj instanceof XmlWebApplicationContext)
        {
            XmlWebApplicationContext context = (XmlWebApplicationContext) obj;
            String nameSpace = context.getNamespace();
            if("DispatcherServlet-servlet".equals(nameSpace) && flag)
            {
                logger.debug("DispatcherServlet-servlet init ok");
                gameNumbersRuleService.initCurrentDateGameRule();
                createCheckJob();
                flag = false;
            }
        }
    }

    private void createCheckJob() {
        ScheduleJob job = new ScheduleJob();
        job.setJobName("gameCheck");
        job.setJobGroup("numberGame");
        job.setJobStatus(ScheduleJob.STATUS_RUNNING);
        //凌晨1点执行检查
        job.setCronExpression("0 0 1 * * ? *");
        job.setDescription("gameCheck");
        job.setBeanClass(TaskCheckGameNumbers.class.getName());
        job.setIsConcurrent(ScheduleJob.CONCURRENT_NOT);
        job.setMethodName("run");
        job.setSpringId("taskCheckGameNumbers");
        try {
            QuartzManager.getInstance().addJob(job);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
